package com.zsk.okhttp;

import java.util.Optional;

import com.alibaba.fastjson.JSON;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * put task
 * @author keke
 * @date 2020/04/23
 */
public class PutTask extends PostTask {

    public PutTask(OkHttpClient client, String url) {
        super(client, url);

    }

    @Override
    protected Request createRequest() {

        requestBuilder.url(urlBuilder.build());
        if (formBodyBuilder != null) {
            requestBuilder.put(formBodyBuilder.build());
        } else {
            // json request
            if (bodyStr != null && !bodyStr.isEmpty()) {
                mediaType = Optional.ofNullable(mediaType).orElse(JSON_TYPE);
                requestBuilder.put(RequestBody.create(mediaType, bodyStr));
            } else if (jsonMap != null && jsonMap.size() > 0) {
                requestBuilder.put(RequestBody.create(JSON_TYPE, JSON.toJSONString(jsonMap)));
            } else {
                requestBuilder.put(RequestBody.create(FORM_TYPE, ""));
            }

        }

        Request request = requestBuilder.build();
        return request;

    }

}
